﻿using MD5Hash;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Security.Cryptography;
using System.Text;

namespace B.S.BasicData.Api.Read.Extensions
{
    public static class Utils
    {

        /// <summary>
        /// 生成一个随机盐值（默认16位）
        /// </summary>
        /// <param name="o"></param>
        /// <param name="size">salt长度</param>
        /// <returns></returns>
        public static string GenerateSalt(this object o, int size = 16)
        {
            using (var rng = RandomNumberGenerator.Create())
            {
                var saltBytes = new byte[size];
                rng.GetBytes(saltBytes);
                return Convert.ToBase64String(saltBytes);
            }
        }  /// <summary>
           /// 随机生成盐值
           /// </summary>
           /// <returns></returns>
        public static string GetSalt(this Object o)
        {
            return Guid.NewGuid().ToString("N").GetMD5();
        }

        /// <summary>
        /// 自定义中间件,注册Jwt
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddJwt(this IServiceCollection services)
        {


            //注册jwt组件
            //授权认证（使用JWT）
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // 私钥
                var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = "BeiJingBW",

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = "BeiJingBW",

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });
            // 配置Swagger
            services.AddSwaggerGen(o =>
            {
                // 显示 授权信息
                o.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
                {
                    Description = "添加JWT授权Token：Bearer Token值",
                    Name = "Authorization",
                    In = Microsoft.OpenApi.Models.ParameterLocation.Header,
                    Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                o.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[]
            {

            }
        }
    });
            });

            return services;
        }
    }
}